import {
  randomString,
  getTimestamp
} from '@/utils'

import Tips from './tips'
import CryptoJS from 'crypto-js'
import Security from './security'

/**
 * 从服务器获取AccessToken的方法
 */
export async function auth () {
  console.group('Auth')
  console.log('执行自动授权...')
  const res = await wxLogin().then(authRequest)
  console.log('微信授权结果:', res)

  const accessToken = res.token.access_token
  wx.setStorageSync('accessToken', accessToken)
  wx.setStorageSync('expiredTime', res.token.expired_at)

  console.log('AccessToken:', accessToken)
  console.groupEnd('Auth')
  return accessToken
}

/**
 * 小程序原生api 获取登录的code属性值
 */
function wxLogin () {
  Tips.loading()
  return new Promise((resolve) => {
    wx.login({
      success: function (res) {
        console.log('微信授权获取Code： ', res)
        const params = generateSignature(res.code)
        console.log('生成签名参数', params)
        return resolve(params)
      }
    })
  })
}

/**
 * 接口登录方法 获取accessToken
 * @param {*} params
 */
function authRequest (params) {
  return new Promise((resolve) => {
    wx.request({
      url: `${process.env.HOST}/authorize/wechat`,
      method: 'POST',
      data: params,
      success: function (res) {
        console.log(res)
        Tips.loaded()
        if (res.data.code === 200) {
          return resolve(res.data.data)
        } else {
          Tips.error(res.data.msg)
        }
      },
      fail: function (e) {
        console.log(e)
      }
    })
  })
}

/**
 * 生成签名字符串
 * @param {*} code
 */
function generateSignature (code) {
  const nonce = randomString(32)
  const systemInfo = wx.getSystemInfoSync()
  let platform = 'android'
  if (iOSDevice(systemInfo.system)) {
    platform = 'ios'
  }
  const model = systemInfo.model

  let params = {
    appid: process.env.APP_ID,
    code: code,
    timestamp: getTimestamp(),
    platform: platform,
    model: model,
    build: 1
  }
  let str = ''
  for (let key of Object.keys(params).sort()) {
    str += params[key]
  }
  let secret = process.env.APP_SECRET
  let sign = CryptoJS.SHA256(secret + str + nonce).toString(CryptoJS.enc.Hex)

  params['nonce'] = nonce
  params['sign'] = sign
  return params
}

/**
 * 判断是否是iOS的设备
 * @param {*} string
 */
function iOSDevice (string) {
  return /^iOS/.test(string)
}

/**
 * 对请求头的token进行AES加密
 * @param {*} data
 */
export function cryptoToken (data) {
  console.log(data)
  return Security.encrypt(data)
}

/**
 * 判断token过期时间，判断是否要重新请求
 */
export function needRequestToken () {
  const expiredTime = wx.getStorageSync('expiredTime')
  if (!expiredTime) {
    return
  }
  const now = new Date().getTime()
  if ((now + 86400 * 5) < expiredTime * 1000) {
    return
  }
  wx.removeStorageSync('accessToken')
  wx.removeStorageSync('expiredTime')
}
